package report

import user.AuthController;

class ActivityController extends AuthController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST", confirm: "POST"]

    def activityService   

    def index = {
    	def today = new Date()
    	def year = params.id ? params.id : today.format('yyyy')
        [activitiesPlannedList: activityService.getPlanned(year), activitiesOngoingList: activityService.getOngoing(year), activitiesFinishedList: activityService.getDone(year), activitiesTotal: activityService.getNumberActivities(), today: today, year: year]
    }

    def list = {
    	def today = new Date()
    	params.max = Math.min(params.max ? params.int('max') : 20, 100)
        [activitiesList: activityService.getActivities(params), activitiesTotal: activityService.getNumberActivities(), today: today, year: today.format('yyyy')]
    }

    def create = {
        def activityInstance = new Activity()
        activityInstance.properties = params
        return [activityInstance: activityInstance, year: new Date().format('yyyy')]
    }

    def save = {
        def activityInstance = new Activity(params)
        if (activityService.save(activityInstance)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'activity.label', default: 'Activity'), activityInstance.id])}"
            redirect(action: "show", id: activityInstance.id)
        } else {
			render(view: "create", model: [activityInstance: activityInstance, year: new Date().format('yyyy')])
        }
    }

    def show = {
        def activityInstance = Activity.get(params.id)
        if (!activityInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'activity.label', default: 'Activity'), params.id])}"
            redirect(action: "list")
        }
        else {
            [activityInstance: activityInstance, year: new Date().format('yyyy')]
        }
    }

    def edit = {
        def activityInstance = Activity.get(params.id)
        if (hasPermission() || activityInstance.sponsors.contains(session.user)) {
	        if (!activityInstance) {
	            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'activity.label', default: 'Activity'), params.id])}"
	            redirect(action: "list")
	        }
	        else {
	            return [activityInstance: activityInstance, year: new Date().format('yyyy')]
	        }
        } else {
        	flash.message = "Você não está autorizado a acessar a página requisitada anteriormente."
			redirect(action: "list")
        }
    }

    def update = {
        def year = new Date().format('yyyy')
    	def activityInstance = Activity.get(params.id)
        if (hasPermission() || activityInstance.sponsors.contains(session.user)) {
	        if (activityInstance) {
	            if (params.version) {
	                def version = params.version.toLong()
	                if (activityInstance.version > version) {
	                    activityInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'activity.label', default: 'Activity')] as Object[], "Another user has updated this Activity while you were editing")
	                    render(view: "edit", model: [activityInstance: activityInstance, year: year])
	                    return
	                }
	            }
	            activityInstance.properties = params
	            if (!activityInstance.hasErrors() && activityService.save(activityInstance)) {
	                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'activity.label', default: 'Activity'), activityInstance.id])}"
	                redirect(action: "show", id: activityInstance.id)
	            }
	            else {
	                render(view: "edit", model: [activityInstance: activityInstance, year: year])
	            }
	        }
	        else {
	            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'activity.label', default: 'Activity'), params.id])}"
	            redirect(action: "list")
	        }
        } else {
    		flash.message = "Você não está autorizado a acessar a página requisitada anteriormente."
			redirect(action: "list")
    	}
    }

    def delete = {
        def activityInstance = Activity.get(params.id)
        if (hasPermission() || activityInstance.sponsors.contains(session.user)) {
	        if (activityInstance) {
	            try {
	            	activityService.delete(activityInstance)
	                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'activity.label', default: 'Activity'), params.id])}"
	                // TODO: redirecionar pra list se ela tiver sido o request anterior
					redirect(action: "index")
	            }
	            catch (org.springframework.dao.DataIntegrityViolationException e) {
	                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'activity.label', default: 'Activity'), params.id])}"
	                redirect(action: "show", id: params.id)
	            }
	        }
	        else {
	            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'activity.label', default: 'Activity'), params.id])}"
				// TODO: redirecionar pra list se ela tiver sido o request anterior
				redirect(action: "index")
	        }
        } else {
    		flash.message = "Você não está autorizado a acessar a página requisitada anteriormente."
			// TODO: redirecionar pra list se ela tiver sido o request anterior
			redirect(action: "index")
    	}
    }
    
    def report = {
    	[activityInstanceList: Activity.list(params), activityInstanceTotal: Activity.count(), year: new Date().format('yyyy')]
    }
    
    def confirm = {
    	if (hasPermission() || activityInstance.sponsors.contains(session.user)) {
	    	def activityInstance = Activity.get(params.id)
	    	activityService.confirm(activityInstance)
    	} else {
    		flash.message = "Você não tem permissão para concluir essa atividade."
    	}
    	redirect(action: "index")
    }
}